package main

import (
	"fmt"
	"io/ioutil"
	"encoding/xml"
)
/*
https://www.cnblogs.com/unqiang/p/10722282.html
https://studygolang.com/static/pkgdoc/pkg/encoding_xml.htm
*/
// 定义结构体映射xml结构
type SConfig struct {
	XMLName  xml.Name `xml:"config"` // 指定最外层的标签为config
	SmtpServer string `xml:"smtpServer"` // 读取smtpServer配置项，并将结果保存到SmtpServer变量中
	SmtpPort int `xml:"smtpPort"`
	Sender string `xml:"sender"`
	SenderPasswd string `xml:"senderPasswd"`
	Receivers SReceivers `xml:"receivers"` // 读取receivers标签下的内容，以结构方式获取
  }
   
  type SReceivers struct {
	Age int `xml:"age"`
	Flag string `xml:"flag,attr"` // 读取flag属性
	User []string `xml:"user"` // 读取user数组
	Script string `xml:"script"` // 读取 <![CDATA[ xxx ]]> 数据
  }

func readXml(path string) {
	// 不用管理打开和关闭，ioutil 在内部已经处理过了
	data, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("读文件出错！", err)
		return
	}
	// fmt.Println(string(bytes))
	v := SConfig{}
	err = xml.Unmarshal(data, &v)
	if err != nil {
	  fmt.Printf("error: %v", err)
	  return
	}
   
	fmt.Println(v)
	fmt.Println("SmtpServer : ",v.SmtpServer)
	fmt.Println("SmtpPort : ",v.SmtpPort)
	fmt.Println("Sender : ",v.Sender)
	fmt.Println("SenderPasswd : ",v.SenderPasswd)
	fmt.Println("Receivers.Flag : ",v.Receivers.Flag)
	fmt.Println("Receivers.Age : ",v.Receivers.Age)
	fmt.Println("Receivers.Script : ",v.Receivers.Script)
	for i,element := range v.Receivers.User {
	  fmt.Println(i,element)
	}
}

func main() {
	readXml("demo.xml")
}